package com.flashcash.kotlin.fragment

import android.app.AlertDialog
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import com.flashcash.kotlin.data.LoanRange
import com.flashcash.kotlin.data.LoaningAmoutBean
import com.flashcash.kotlin.data.ProductBean
import com.flashcash.kotlin.utils.FirebaseAnalyticsConstants
import com.flashcash.kotlin.utils.FirebaseAnalyticsUtils
import com.flashcash.solu.R
import com.flashcash.solu.bean.LatestLoanAppBean
import com.flashcash.solu.bean.TotalAmount
import com.flashcash.solu.broadcast.InstallReferrerReceiver
import com.flashcash.solu.common.EventCollection
import com.flashcash.solu.common.FieldParams
import com.flashcash.solu.common.FieldParamsInt
import com.flashcash.solu.common.TokenManager
import com.flashcash.solu.utils.InstallReferrelHelper
import com.flashcash.solu.utils.StringFormatUtils
import com.flashcash.solu.view.MainActivity
import com.flashcash.solu.view.camera.FaceDetectorFragment
import com.flashcash.solu.view.fragment.LoanNormalView
import com.flashcash.solu.view.fragment.presenter.LoanNormalFraPreImp
import com.flashcash.solu.view.fragment.presenter.LoanNormalFraPresenter
import com.flashcash.solu.widget.XLeoSp
import com.jakewharton.rxbinding.widget.RxRadioGroup
import com.x.leo.apphelper.data.cache.CacheDataManage
import com.x.leo.apphelper.log.XLog
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk25.coroutines.onClick
import rx.Observable
import rx.android.schedulers.AndroidSchedulers

/**
 * Created by XLEO on 2017/12/11.
 */
class LoanNormalFragment1 : FaceDetectorFragment<LoanNormalFraPresenter>(), LoanNormalView {
    companion object {
        const val TAG = "LoanNormalFragment1"

        private const val EXTRA_PRODUCT_BEAN = "productBean"

        fun newInstance(productBean: ProductBean): LoanNormalFragment1 {
            val bundle = Bundle()
            bundle.putSerializable(EXTRA_PRODUCT_BEAN, productBean)
            val instance = LoanNormalFragment1()
            instance.arguments = bundle

            return instance
        }
    }

    override fun doPreBuildHeader(): Boolean {
        return true
    }

    override fun getTitle(): String {
        return "Loan Info"
    }

    override fun showMessageIcon(): Boolean {
        return false
    }

    /*override fun showBack(): Boolean {
        return true
    }*/

    override fun getBackPressListener(): View.OnClickListener {
        return View.OnClickListener { activity!!.finish() }
    }

    private lateinit var moneyRadioGroup: RadioGroup
    private lateinit var termRadioGroup: RadioGroup
    private lateinit var moneyRadioButton01: RadioButton
    private lateinit var moneyRadioButton02: RadioButton
    private lateinit var termRadioButton01: RadioButton
    private lateinit var termRadioButton02: RadioButton

    private lateinit var issueAmountTextView: TextView
    private lateinit var repaymentAmountTextView: TextView
    private lateinit var repaymentTermTextView: TextView
    private lateinit var repaymentServiceFeeTextView: TextView
    private lateinit var repaymentInterestTextView: TextView

    private lateinit var currentLoanButton: Button
//    private lateinit var repaymentInstructionTextView: TextView


    private lateinit var productBean: ProductBean
    private var selectedAmount: Double = 0.0
    private var selectedPeriod: Int = 0

    fun setProductBean(productBean: ProductBean) {
        this.productBean = productBean

        this.selectedAmount = this.productBean.minAmount
        this.selectedPeriod = this.productBean.minPeriod

        refreshUI()
    }

    private fun refreshUI() {
        Log.d(TAG, "refreshUI()")

        moneyRadioButton01.apply {
            text = "PHP " + StringFormatUtils.moneyFormatWithSplitWithUnitWithoutDecimal(productBean.minAmount, context)
        }

        moneyRadioButton02.apply {
            text = "PHP " + StringFormatUtils.moneyFormatWithSplitWithUnitWithoutDecimal(productBean.maxAmount, context)
            visibility = if (productBean.maxAmount == productBean.minAmount) {
                // change amount RadioGroup's background
//                moneyRadioGroup.background = null
                View.GONE
            } else {
                // change amount RadioGroup's background
                // moneyRadioGroup.background = ContextCompat.getDrawable(mActivity, R.drawable.shape_radio_group_background)
                View.VISIBLE
            }
        }

        termRadioButton01.apply {
            text = StringFormatUtils.periodFormat(context, productBean.minPeriod.toDouble(), productBean.periodUnit)
        }

        termRadioButton02.apply {
            text = StringFormatUtils.periodFormat(context, productBean.maxPeriod.toDouble(), productBean.periodUnit)
            visibility = if (productBean.maxPeriod == productBean.minPeriod) {
                // change term RadioGroup's background
//                termRadioGroup.background = null
                View.GONE
            } else {
                // change term RadioGroup's background
                // termRadioGroup.background = ContextCompat.getDrawable(mActivity, R.drawable.shape_radio_group_background)
                View.VISIBLE
            }
        }

        val moneyChanges = RxRadioGroup.checkedChanges(moneyRadioGroup)
        val termChanges = RxRadioGroup.checkedChanges(termRadioGroup)
        Observable.combineLatest(moneyChanges, termChanges) { i: Int?, i2: Int? -> Pair(i, i2) }.subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    /*when (it.first) {
                        R.id.rb_money_01 -> {
                            moneyRadioButton01.background = ContextCompat.getDrawable(mActivity, R.drawable.button_bg)
                            moneyRadioButton01.textColor = ContextCompat.getColor(mActivity,R.color.white)
                            moneyRadioButton02.background = ContextCompat.getDrawable(mActivity, R.drawable.button_line)
                            moneyRadioButton02.textColor = ContextCompat.getColor(mActivity,R.color.theme_green)

                            if (selectedAmount != productBean.minAmount) {
                                selectedAmount = productBean.minAmount
                            }
                        }
                        R.id.rb_money_02 -> {
                            moneyRadioButton01.background = ContextCompat.getDrawable(mActivity, R.drawable.button_line)
                            moneyRadioButton01.textColor = ContextCompat.getColor(mActivity,R.color.theme_green)
                            moneyRadioButton02.background = ContextCompat.getDrawable(mActivity, R.drawable.button_bg)
                            moneyRadioButton02.textColor = ContextCompat.getColor(mActivity,R.color.white)

                            if (selectedAmount != productBean.maxAmount) {
                                selectedAmount = productBean.maxAmount
                            }
                        }
                        else -> {
                        }
                    }
                    when (it.second) {
                        R.id.rb_term_01 -> {
                            termRadioButton01.background = ContextCompat.getDrawable(mActivity, R.drawable.button_bg)
                            termRadioButton01.textColor = ContextCompat.getColor(mActivity,R.color.white)
                            termRadioButton02.background = ContextCompat.getDrawable(mActivity, R.drawable.button_line)
                            termRadioButton02.textColor = ContextCompat.getColor(mActivity,R.color.theme_green)

                            if (selectedPeriod != productBean.minPeriod) {
                                selectedPeriod = productBean.minPeriod
                            }
                        }
                        R.id.rb_term_02 -> {
                            termRadioButton01.background = ContextCompat.getDrawable(mActivity, R.drawable.button_line)
                            termRadioButton01.textColor = ContextCompat.getColor(mActivity,R.color.theme_green)
                            termRadioButton02.background = ContextCompat.getDrawable(mActivity, R.drawable.button_bg)
                            termRadioButton02.textColor = ContextCompat.getColor(mActivity,R.color.white)

                            if (selectedPeriod != productBean.maxPeriod) {
                                selectedPeriod = productBean.maxPeriod
                            }
                        }
                        else -> {
                        }
                    }*/

                    mPresenter.getCurrentLoanResult(selectedAmount, selectedPeriod.toDouble(), productBean.periodUnit, productBean.id)
                }

        currentLoanButton.apply {
            onClick {
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_APPLY, null)

                XLog.d("LoanNormalFragment current loan clicked! token: " + TokenManager.getInstance().token, 10)

                val loanData = TotalAmount()
                loanData.amount = selectedAmount
                loanData.day = selectedPeriod
                loanData.setRate((productBean.interestRate * 100).toInt())
                loanData.periodUnit = productBean.periodUnit
                loanData.productId = productBean.id
                CacheDataManage.addData(FieldParamsInt.TO_LOAN_DATA, EventCollection.GotoLoanApplicationTabEvent(loanData))
                CacheDataManage.addData(FieldParamsInt.TOTAL_AMOUNT, loanData)

                MainActivity.isSubmitVisible = true
                mPresenter.qualificateLoan()
            }
        }

        /*repaymentInstructionTextView.onClick {
            startActivity(Intent(getContext(), RepaymentRaidersInstruction2::class.java))
        }*/

        val latestLoanAppBean = CacheDataManage.obtainData(FieldParamsInt.LATESTBEAN, LatestLoanAppBean::class.java)
        if (latestLoanAppBean != null && FieldParams.LoanStatus.SUBMITTED == latestLoanAppBean.status && TokenManager.getInstance().hasLogin()) {
            if (productBean.minAmount == latestLoanAppBean.amount) {
                moneyRadioButton01.apply {
                    isChecked = true
                    isClickable = true
                }
                moneyRadioButton02.apply {
                    isChecked = false
                    isClickable = false
                }
            } else {
                moneyRadioButton01.apply {
                    isChecked = false
                    isClickable = false
                }
                moneyRadioButton02.apply {
                    isChecked = true
                    isClickable = true
                }
            }

            if (productBean.minPeriod == latestLoanAppBean.period) {
                termRadioButton01.apply {
                    isChecked = true
                    isClickable = true
                }
                termRadioButton02.apply {
                    isChecked = false
                    isClickable = false
                }
                repaymentTermTextView.text = termRadioButton01.text
            } else {
                termRadioButton01.apply {
                    isChecked = false
                    isClickable = false
                }
                termRadioButton02.apply {
                    isChecked = true
                    isClickable = true
                }
                repaymentTermTextView.text = termRadioButton02.text
            }
        } else {
            moneyRadioButton01.isChecked = true
            termRadioButton01.isChecked = true

            moneyRadioButton01.isClickable = true
            moneyRadioButton02.isClickable = true

            termRadioButton01.isClickable = true
            termRadioButton02.isClickable = true

            repaymentTermTextView.text = termRadioButton01.text
        }

        if (TokenManager.getInstance().hasLogin()) {
            if (latestLoanAppBean != null && FieldParams.LoanStatus.SUBMITTED == latestLoanAppBean.status) {
                currentLoanButton.text = getString(R.string.goto_add_withdraw_channel)
            } else {
                currentLoanButton.text = getString(R.string.button_current_loan)
            }
        } else {
            currentLoanButton.text = getString(R.string.button_current_loan)
        }
    }

    override fun submitButtonStateUpdate(active: Boolean) {}

    override fun updateTotalAmout(loaningAmoutBean: LoaningAmoutBean?) {
//        find<TextView>(R.id.id_textview_unloan_total_repayment).apply {
//            text = StringFormatUtils.moneyFormatWithSplitWithUnitWithoutDecimal(loaningAmoutBean!!.dueAmount!!, context)
//        }

        issueAmountTextView.apply {
            text = "PHP " + StringFormatUtils.moneyFormatWithSplitWithUnitWithoutDecimal(loaningAmoutBean!!.issueAmount!!, context)
        }

        repaymentAmountTextView.apply {
            text = "PHP " + StringFormatUtils.moneyFormatWithSplitWithUnitWithoutDecimal(loaningAmoutBean!!.dueAmount!!, context)
        }

        repaymentServiceFeeTextView.apply {
            text = "PHP " + StringFormatUtils.moneyFormatWithSplitWithUnitWithoutDecimal(loaningAmoutBean!!.serviceFee!!, context)
        }

        repaymentInterestTextView.apply {
            text = "PHP " + StringFormatUtils.moneyFormatWithSplitWithUnitWithoutDecimal(loaningAmoutBean!!.interest!!, context)
        }

        /* repaymentTermTextView.apply {
             text = StringFormatUtils.moneyFormatWithSplitWithUnitWithoutDecimal(loaningAmoutBean!!.dueAmount!!, context)
         }*/
    }

    override fun onSpanObtain(isInitData: Boolean, loanRange: LoanRange?) {

    }

    override fun onSpanObtainError() {
        if (isVisible) {
            AlertDialog.Builder(context).setTitle(R.string.tips_title).setMessage(R.string.network_error)
                    .setPositiveButton(R.string.retry) { dialog, _ ->
                        dialog.dismiss()
                        mPresenter.requestDataSpan()
                    }.create().show()
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        Log.d(TAG, "onHiddenChanged()")
        if (!hidden) {
            checkReferrer()
        }
    }

    override fun toReLogin() {
        toLogin()
    }

    override fun initPresenter(): LoanNormalFraPresenter {
        return LoanNormalFraPreImp()
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_loan_normal_1
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        moneyRadioGroup = view.find(R.id.rg_money)
        termRadioGroup = view.find(R.id.rg_term)
        moneyRadioButton01 = view.find(R.id.rb_money_01)
        moneyRadioButton02 = view.find(R.id.rb_money_02)
        termRadioButton01 = view.find(R.id.rb_term_01)
        termRadioButton02 = view.find(R.id.rb_term_02)

        issueAmountTextView = view.find(R.id.tv_issue_amount)
        repaymentAmountTextView = view.find(R.id.id_textview_repayment_amount)
        repaymentTermTextView = view.find(R.id.id_textview_repayment_term)
        repaymentServiceFeeTextView = view.find(R.id.id_textview_repayment_service_fee)
        repaymentInterestTextView = view.find(R.id.id_textview_repayment_interest)

        currentLoanButton = view.find(R.id.id_button_current_loan_u)
//        repaymentInstructionTextView = view.find(R.id.id_textview_repayment_instruction)
    }

    override fun initData() {
        checkReferrer()
        if (arguments != null) {
            val productBean = arguments!!.getSerializable(EXTRA_PRODUCT_BEAN)
            if (productBean != null) {
                setProductBean(productBean as ProductBean)
            }
        }
        /*mPresenter.requestDataSpan()*/
    }

    private var installReferrelHelper: InstallReferrelHelper? = null

    fun checkReferrer() {
        // when first launch flag is set (and get install referrer only once)
        if (installReferrelHelper == null) {
            subscribeInstallReferrerListener()
        }
        // referrer is received in subscribeInstallReferrerListener
        installReferrelHelper!!.getReferrerAsync(this.baseActivity)
    }

    private fun subscribeInstallReferrerListener() {
        installReferrelHelper = InstallReferrelHelper()
        installReferrelHelper!!.setOnInstallReferrerListener { referrer ->
            if (!TextUtils.isEmpty(referrer)) {
                XLeoSp.getInstance(context).putString(InstallReferrerReceiver.install_referrer_from_ga_sdk_store_key, referrer)
            }
        }
    }
}